package com.example.muyonghui.mytimetable;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class AddInfoByHttpActivity extends AppCompatActivity {


    public static final int SHOW_RESPONSE = 0;

    private EditText schoolcode;

    private EditText password;

    private EditText checkcode;

    private ImageButton img;

    private Button login;

    private MyDatabaseHelper dbHelper;

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:

                    BitmapFactory.Options options = new  BitmapFactory.Options();
                    options.inSampleSize = 1/2 ;
                    byte[] data = (byte[]) msg.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    Matrix matrix= new Matrix();
                    matrix.postScale(4f,4f);
                    Bitmap temp=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
                    bitmap= temp;
//                    String response = (String) msg.obj;
//                    Bitmap bitmap = BitmapFactory.decodeByteArray( msg.obj);
                    // 在这里进行UI操作，将结果显示到界面上
                    img.setImageBitmap(bitmap);
                    Log.d("aaaaaa","aaaaaaa");
            }
        }

    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcourse);

        dbHelper = new MyDatabaseHelper(this, "UserStore.db", null, 3);

        schoolcode = (EditText) findViewById(R.id.school_code);
        password = (EditText) findViewById(R.id.school_password);
        checkcode = (EditText) findViewById(R.id.school_checkcode);
        img = (ImageButton) findViewById(R.id.checkcode);
        login = (Button) findViewById(R.id.school_login);
        sendRequestWithHttpURLConnection();
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRequestWithHttpURLConnection();


            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String schoolcodeTxt = schoolcode.getText().toString();
                String passwordTxt = password.getText().toString();
                String checkcodeTxt = checkcode.getText().toString();
                sendRequestWithHttpURLConnectionTwo(schoolcodeTxt,passwordTxt,checkcodeTxt);
//                HttpUtil.sendHttpRequest("http://10.0.2.2:3000/test",schoolcodeTxt,passwordTxt,checkcodeTxt, new HttpCallbackListener() {
//                    @Override
//                    public void onFinish(String response) {
//                        // 在这里根据返回内容执行具体的逻辑
//                        Log.d("aa",""+response);
//                    }
//
//                    @Override
//                    public void onError(Exception e) {
//                        // 在这里对异常情况进行处理
//                        Log.d("bb",""+e);
//                    }
//                });
                Toast.makeText(AddInfoByHttpActivity.this, "已全部存储",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setClass(AddInfoByHttpActivity.this, MainActivity.class);
                AddInfoByHttpActivity.this.startActivity(intent);
                finish();

            }
        });


        //HttpClient httpClient = new DefaultHttpClient();
    }

    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://10.0.2.2:3000/getCheckCode");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    // 下面对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                    byte[] data = StreamTool.readInputStream(in);     //获得图片的二进制数据


                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Log.d("sss",""+response);
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    // 将服务器返回的结果存放到Message中
                    message.obj = data;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void sendRequestWithHttpURLConnectionTwo(final String usernametxt,final String passwordtxt,final String checkcodetxt) {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://10.0.2.2:3000/loginAndGetCourses");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes("username="+usernametxt+"&password="+passwordtxt+"&checkCode=" +checkcodetxt);
                    InputStream in = connection.getInputStream();
                    // 下面对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));



                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Log.d("sss",""+response);
                    parseJSONWithJSONObject(response.toString());

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    private void parseJSONWithJSONObject(String jsonData) {
        try {

            //数据格式
            /*[
  { coursename: '专业见习',
    teachername: '指导组（服）',
    time: '',
    address: '' },
  { coursename: 'JSP/Servlet程序设计',
    teachername: '石兴民',
    time: '周二第4,5节{第1-16周};周四第3节{第1-16周};周四第4节{第1-16周}',
    address: ';;' },
  { coursename: '职业素养',
    teachername: '胡保坤',
    time: '周一第6,7节{第9-16周}',
    address: '' } ]*/
            Log.d("sss",""+jsonData);
            JSONArray jsonArray = new JSONArray(jsonData);
            SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
            String username = pref.getString("username", "");
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject courseInfo = jsonArray.getJSONObject(i);
                String coursename = courseInfo.getString("coursename");
                String teachername = courseInfo.getString("teachername");
                String time = courseInfo.getString("time");
                String address = courseInfo.getString("address");


                // 开始组装第一条数据
                values.put("username", username);
                values.put("course_name", coursename);
                values.put("course_teacher", teachername);
                values.put("course_time", time);
                values.put("course_address", address);
                db.insert("course", null, values); // 插入数据
                values.clear();
            }



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
